cap program drop balancetable
program define balancetable
syntax varlist  [if/],using(str asis) sheet(str asis) by(varname)[ subpop(str asis) *]
 global tflist ""
 global modseq=0
 global varseq=0
 if "`if'"!="" {
 	 local if "if `if'"
 } 
 
 if "`subpop'"!="" {
 	 local subpop ",subpop(`subpop')"
 } 
 preserve
 foreach y of var `varlist' {
 
	global modseq=$modseq+1
	global varseq=$varseq+1
	tempfile tf$modseq 
	qui parmby "svy `subpop': mean `y' `if'", by(`by') label format(estimate  min95 max95 %8.2f p %8.1e) idn($varseq) ev(_N) saving(`tf$modseq',replace) flist(tflist)
	
	global modseq=$modseq+1
	tempfile tf$modseq
	qui svy `subpop': mean `y' `if', over(`by')
	qui lincomest  c.`y'@1.`by'-c.`y'@0.`by' 
   qui parmest, label idn($varseq) saving(`tf$modseq') ev(_N) flist(tflist)
   }
 dsconcat $tflist 
 *create column variable 1=Not National , 2 National, 3 Diff
 gen col=`by'+1
 replace col=3 if col==.
replace label=label[_n-1] if col==3
replace ev_1=ev_1[_n-1]+ ev_1[_n-2] if col==3
rename ev_1 n
encode label, gen(var)

keep estimate p n var col idnum
reshape wide estimate n p idnum, i(var) j(col)
sort idnum1

rename estimate1 Not_`by'
rename estimate2 `by'
rename estimate3 Difference
rename n3 n
rename p3 pvalue
format pvalue %16.0g
replace pvalue=round(pvalue, .0001)
drop *1 *2 *3
export excel using `using', sheet(" `sheet'", replace) firstrow(variables)
restore
end

cap program drop balancetablesch
program define balancetablesch
syntax varlist  [if/],using(str asis) sheet(str asis) by(varname)  [*]
 global tflist ""
 global modseq=0
 global varseq=0
 if "`if'"!="" {
 	 local if "if `if'"
 } 
 preserve
 foreach y of var `varlist' {
 
	global modseq=$modseq+1
	global varseq=$varseq+1
	tempfile tf$modseq 
	qui parmby "mean `y' `if'", by(`by') label format(estimate  min95 max95 %8.2f p %8.1e) idn($varseq) ev(_N) saving(`tf$modseq',replace) flist(tflist)
	
	global modseq=$modseq+1
	tempfile tf$modseq
	qui mean `y' `if', over(`by')
	qui lincomest  c.`y'@1.`by'-c.`y'@0.`by' 
   qui parmest, label idn($varseq) saving(`tf$modseq') ev(_N) flist(tflist)
   }
 dsconcat $tflist 
 *create column variable 1=Not National , 2 National, 3 Diff
 gen col=`by'+1
 replace col=3 if col==.
replace label=label[_n-1] if col==3
replace ev_1=ev_1[_n-1]+ ev_1[_n-2] if col==3
rename ev_1 n
encode label, gen(var)

keep estimate p n var col idnum
reshape wide estimate n p idnum, i(var) j(col)
sort idnum1

rename estimate1 Not_`by'
rename estimate2 `by'
rename estimate3 Difference
rename n3 n
rename p3 pvalue
format pvalue %16.0g
replace pvalue=round(pvalue, .0001)
drop *1 *2 *3
export excel using `using', sheet("`sheet' ", replace) firstrow(variables)
restore
end